/** @format */

import { useNavigate, useParams } from 'react-router-dom'
import { NavBar } from 'antd-mobile'

import ArticleItem from '@/components/ArticleItem'

import styles from './List.module.scss'
import { SearchParams, SearchResultItem } from '@/types/http'
import { useEffect, useRef, useState } from 'react'
import { getSearchResultApi } from '@/api/search'

const List = () => {
  const navigate = useNavigate()

  // 获取动态路由参数
  const params = useParams<{
    txt: string
  }>()
  // 搜索分页参数
  const searchQuery = useRef<SearchParams>({
    page: 1,
    per_page: 10,
    q: params.txt || ''
  })
  // 搜索结果列表
  const [searchList, setSearchList] = useState<SearchResultItem[]>([])

  useEffect(() => {
    getSearchResult()
    async function getSearchResult() {
      const {
        data: {
          data: { results }
        }
      } = await getSearchResultApi(searchQuery.current)
      setSearchList(results)
    }
  }, [])

  const renderArticleList = () => {
    return searchList.map((item, index) => {
      return (
        <div
          key={index}
          className='article-item'
          onClick={() => navigate(`/article/`)}>
          <ArticleItem {...item} />
        </div>
      )
    })
  }

  return (
    <div className={styles.root}>
      <NavBar onBack={() => navigate(-1)}>搜索结果</NavBar>
      <div className='article-list'>{renderArticleList()}</div>
    </div>
  )
}

export default List
